package server

import (
	"context"
	"fmt"
	"github.com/spf13/cast"
	"longmen/server/config/global"
	"longmen/server/internal/rpc/games/dice_machine"
	"longmen/server/pkg/common/helper/timehelper"
	pb "longmen/server/pkg/protobuf"
)

func (s *GameServer) DiceAction(ctx context.Context, req *pb.DiceActionReq) (*pb.DiceActionResp, error) {
	global.Log.Debugf("下注数据:%v", cast.ToString(req))
	req.BetNum *= 100
	resp := &pb.DiceActionResp{}

	d, err := dice_machine.NewDice(int(req.GetChoices()), int(req.GetBetNum()), req.GetIsRollDown(), req.GetTag())
	if err != nil {
		return resp, err
	}
	uh := dice_machine.NewDiceUser(int(req.UserId))
	//检查
	err = d.Before(uh)
	if err != nil {
		return resp, err
	}
	//进行游戏
	d.Play()
	//扣除余额
	err = d.After(uh)
	if err != nil {
		return resp, err
	}

	//查询批次记录
	batchResp := uh.GetDiceBatchReward(req.Tag)

	resp = &pb.DiceActionResp{
		RollNum:       int32(d.R.RollNum),
		Odds:          fmt.Sprintf("%.4f", d.R.Odds),
		IsReward:      d.R.IsReward,
		RewardNum:     transAmount(d.R.RewardNum),
		AwardNum:      transAmount(d.R.RewardNum - int(req.BetNum)),
		BatchAwardNum: transAmount(batchResp.BatchAwardNum),
		BatchTimes:    int32(batchResp.BatchTimes),
		Req:           req,
	}
	req.BetNum /= 100
	global.Log.Debugf("开奖数据:%v", cast.ToString(resp))
	return resp, err
}

func (s *GameServer) DiceHistory(ctx context.Context, req *pb.DiceHistoryReq) (*pb.DiceHistoryResp, error) {
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.Size <= 0 {
		req.Size = 10
	}
	uh := dice_machine.NewDiceUser(int(req.UserId))
	total, betNumTotal, rewardNumTotal, his, err := uh.GetDiceFlow(int(req.Page), int(req.Size), req.DateSt, req.DateEd)
	if err != nil {
		return &pb.DiceHistoryResp{}, err
	}
	resp := &pb.DiceHistoryResp{
		Total:          total,
		BetNumTotal:    transAmount(betNumTotal),
		RewardNumTotal: transAmount(rewardNumTotal),
	}
	for _, v := range his {
		resp.DiceResult = append(resp.DiceResult, &pb.DiceResult{
			Choices:    int32(v.Choices),
			IsRollDown: v.IsRollDown,
			RollNum:    int32(v.RollNum),
			Odds:       fmt.Sprintf("%.4f", v.Odds),
			BetNum:     transAmount(v.BetNum),
			RewardNum:  transAmount(v.RewardNum),
			DiceTime:   timehelper.Stamp2FullStr(v.Ctime),
			AwardNum:   transAmount(v.AwardAmount),
			Tag:        v.Tag,
		})
	}
	return resp, nil
}

func transAmount(i int) float32 {
	if i == 0 {
		return 0.0
	}
	return float32(i) / 100.0
}
